import pygame
import sys
import random

# 初始化pygame
pygame.init()

# 设置屏幕大小
screen_size = (640, 480)
screen = pygame.display.set_mode(screen_size)

# 设置游戏标题
pygame.display.set_caption("贪吃蛇")

# 定义颜色
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

# 蛇的初始位置
snake_pos = [[100, 100], [80, 100], [60, 100]]

# 食物的初始位置
food_pos = [300, 300]

# 蛇的初始速度
snake_speed = [20, 0]

# 初始化得分为0
score = 0

# 主循环
while True:
    # 绘制游戏界面
    screen.fill(WHITE)

    # 处理游戏事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                snake_speed = [0, -20]
            elif event.key == pygame.K_DOWN:
                snake_speed = [0, 20]
            elif event.key == pygame.K_LEFT:
                snake_speed = [-20, 0]
            elif event.key == pygame.K_RIGHT:
                snake_speed = [20, 0]

    # 更新蛇的位置
    snake_pos.insert(0, [snake_pos[0][0] + snake_speed[0], snake_pos[0][1] + snake_speed[1]])

    # 检查蛇头是否碰到食物
    if snake_pos[0] == food_pos:
        food_pos = [random.randrange(1, screen_size[0] // 20) * 20, random.randrange(1, screen_size[1] // 20) * 20]
        score += 1  # 每次吃到食物，得分加1
    else:
        snake_pos.pop()

    # 检查蛇头是否碰到墙壁或者蛇身
    if snake_pos[0][0] < 0 or snake_pos[0][0] >= screen_size[0] or snake_pos[0][1] < 0 or snake_pos[0][1] >= \
            screen_size[1] or snake_pos[0] in snake_pos[1:]:
        over_text = pygame.font.Font(None, 36).render("Game Over", True, (255, 0, 0))
        screen.blit(over_text, (320, 240))
        pygame.display.flip()
        print("we")
        flag = True
        while flag:
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_RETURN:
                        print("Enter 按钮被按下了！")
                        snake_pos = [[100, 100], [80, 100], [60, 100]]
                        food_pos = [300, 300]
                        flag = False
                    elif event.key == pygame.K_ESCAPE:
                        print("ESC 按钮被按下了！")
                        pygame.quit()
                        sys.exit()

    print("shd")
    # 在屏幕上显示得分
    score_text = pygame.font.Font(None, 36).render(f"score:{score}", True, (255, 0, 0))
    screen.blit(score_text, (10, 10))

    for pos in snake_pos:
        pygame.draw.rect(screen, GREEN, pygame.Rect(pos[0], pos[1], 20, 20))

    pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], 20, 20))

    pygame.display.flip()

    # 控制游戏速度
    pygame.time.Clock().tick(10)
